package com.sunchangming.stmdb;

import java.lang.management.ManagementFactory;
import java.rmi.registry.LocateRegistry;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyMbeanServer implements Module {
	private static volatile MyMbeanServer instance;

	public static MyMbeanServer getInstance() {
		if (instance == null) {
			synchronized (MyMbeanServer.class) {
				if (instance == null)
					instance = new MyMbeanServer();
			}
		}
		return instance;
	}

	private static final Logger logger = LoggerFactory.getLogger(MyMbeanServer.class);
	private MBeanServer mBeanServer;
	private JMXConnectorServer cs;

	public synchronized void register(Object obj) throws Exception {
		mBeanServer.registerMBean(obj, new ObjectName("com.tianshen:type=xiyou,name="
				+ obj.getClass().getCanonicalName()));
	}

	@Override
	public synchronized void init() throws Exception {
		instance = this;
		mBeanServer = ManagementFactory.getPlatformMBeanServer();
		final int port1 = 14000; //the port number on which the RMIServer and RMIConnection remote objects are exported
		final int port2 = 15000; //the port number of the RMI Registry
		LocateRegistry.createRegistry(port2);
		final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://0.0.0.0:" + port1 + "/jndi/rmi://:" + port2
				+ "/jmxrmi");
		final java.util.HashMap<String, Object> env = new java.util.HashMap<String, Object>();
		cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mBeanServer);
		cs.start();
	}

	@Override
	public synchronized void fini() {
		try {
			cs.stop();
		} catch (final java.io.IOException ex) {
			logger.error("err", ex);
		}
	}

}
